<template>
  <div class="chat-container">
    <!-- 聊天室列表 -->
    <div class="chat-sidebar">
      <div class="sidebar-header">
        <h3>聊天室</h3>
        <el-button type="primary" size="small" @click="showCreateRoom = true">
          创建房间
        </el-button>
      </div>
      <div class="room-list">
        <div 
          v-for="room in chatRooms"
          :key="room.id"
          class="room-item"
          :class="{ active: currentRoom?.id === room.id }"
          @click="joinRoom(room)"
        >
          <div class="room-info">
            <h4>{{ room.name }}</h4>
            <p>{{ room.memberCount }}人在线</p>
          </div>
          <div class="room-status">
            <el-badge :value="room.unreadCount" :hidden="room.unreadCount === 0" />
          </div>
        </div>
      </div>
    </div>

    <!-- 聊天主区域 -->
    <div class="chat-main">
      <div v-if="!currentRoom" class="no-room">
        <el-empty description="请选择一个聊天室开始聊天" />
      </div>
      <div v-else class="chat-content">
        <!-- 聊天头部 -->
        <div class="chat-header">
          <div class="room-info">
            <h3>{{ currentRoom.name }}</h3>
            <p>{{ currentRoom.memberCount }}人在线</p>
          </div>
          <div class="room-actions">
            <el-button size="small" @click="showMembers = true">成员列表</el-button>
            <el-button size="small" @click="leaveRoom">离开房间</el-button>
          </div>
        </div>

        <!-- 消息列表 -->
        <div class="message-list" ref="messageContainer">
          <div 
            v-for="message in messages"
            :key="message.id"
            class="message-item"
            :class="{ 'own-message': message.userId === currentUserId }"
          >
            <el-avatar :size="32" :src="message.userAvatar" />
            <div class="message-content">
              <div class="message-header">
                <span class="username">{{ message.username }}</span>
                <span class="time">{{ formatTime(message.createTime) }}</span>
              </div>
              <div class="message-text">{{ message.content }}</div>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="message-input">
          <el-input
            v-model="inputMessage"
            type="textarea"
            :rows="3"
            placeholder="输入消息..."
            @keydown.enter.exact="sendMessage"
          />
          <el-button type="primary" @click="sendMessage" :disabled="!inputMessage.trim()">
            发送
          </el-button>
        </div>
      </div>
    </div>

    <!-- 创建房间对话框 -->
    <el-dialog v-model="showCreateRoom" title="创建聊天室" width="500px">
      <el-form :model="roomForm" label-width="80px">
        <el-form-item label="房间名称">
          <el-input v-model="roomForm.name" placeholder="请输入房间名称" />
        </el-form-item>
        <el-form-item label="房间描述">
          <el-input v-model="roomForm.description" type="textarea" placeholder="请输入房间描述" />
        </el-form-item>
        <el-form-item label="房间类型">
          <el-radio-group v-model="roomForm.type">
            <el-radio value="PUBLIC">公开</el-radio>
            <el-radio value="PRIVATE">私有</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateRoom = false">取消</el-button>
        <el-button type="primary" @click="createRoom">创建</el-button>
      </template>
    </el-dialog>

    <!-- 成员列表对话框 -->
    <el-dialog v-model="showMembers" title="房间成员" width="400px">
      <div class="member-list">
        <div 
          v-for="member in roomMembers"
          :key="member.id"
          class="member-item"
        >
          <el-avatar :size="32" :src="member.avatar" />
          <span class="member-name">{{ member.username }}</span>
          <el-tag v-if="member.isOnline" type="success" size="small">在线</el-tag>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { 
  getChatRooms,
  createChatRoom,
  joinChatRoom,
  leaveChatRoom,
  getChatMessages,
  sendMessage as apiSendMessage,
  getChatRoomMembers
} from '@/api/chat'

const userStore = useUserStore()

// 响应式数据
const chatRooms = ref([])
const currentRoom = ref(null)
const messages = ref([])
const roomMembers = ref([])
const inputMessage = ref('')
const showCreateRoom = ref(false)
const showMembers = ref(false)
const messageContainer = ref()

// 表单数据
const roomForm = reactive({
  name: '',
  description: '',
  type: 'PUBLIC'
})

// 当前用户ID
const currentUserId = userStore.userInfo?.id

// 获取聊天室列表
const loadChatRooms = async () => {
  try {
    const response = await getChatRooms()
    if (response.code === 200) {
      chatRooms.value = response.data
    }
  } catch (error) {
    console.error('获取聊天室列表失败:', error)
  }
}

// 加入房间
const joinRoom = async (room) => {
  try {
    await joinChatRoom(room.id)
    currentRoom.value = room
    await loadMessages()
    await loadMembers()
  } catch (error) {
    console.error('加入房间失败:', error)
    ElMessage.error('加入房间失败')
  }
}

// 离开房间
const leaveRoom = async () => {
  if (!currentRoom.value) return
  
  try {
    await leaveChatRoom(currentRoom.value.id)
    currentRoom.value = null
    messages.value = []
    roomMembers.value = []
  } catch (error) {
    console.error('离开房间失败:', error)
    ElMessage.error('离开房间失败')
  }
}

// 加载消息
const loadMessages = async () => {
  if (!currentRoom.value) return
  
  try {
    const response = await getChatMessages(currentRoom.value.id)
    if (response.code === 200) {
      messages.value = response.data
      await nextTick()
      scrollToBottom()
    }
  } catch (error) {
    console.error('加载消息失败:', error)
  }
}

// 加载成员
const loadMembers = async () => {
  if (!currentRoom.value) return
  
  try {
    const response = await getChatRoomMembers(currentRoom.value.id)
    if (response.code === 200) {
      roomMembers.value = response.data
    }
  } catch (error) {
    console.error('加载成员失败:', error)
  }
}

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim() || !currentRoom.value) return
  
  try {
    const response = await apiSendMessage(currentRoom.value.id, {
      content: inputMessage.value
    })
    
    if (response.code === 200) {
      messages.value.push(response.data)
      inputMessage.value = ''
      await nextTick()
      scrollToBottom()
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败')
  }
}

// 创建房间
const createRoom = async () => {
  try {
    const response = await createChatRoom(roomForm)
    if (response.code === 200) {
      showCreateRoom.value = false
      Object.assign(roomForm, { name: '', description: '', type: 'PUBLIC' })
      await loadChatRooms()
      ElMessage.success('创建成功')
    }
  } catch (error) {
    console.error('创建房间失败:', error)
    ElMessage.error('创建房间失败')
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (messageContainer.value) {
    messageContainer.value.scrollTop = messageContainer.value.scrollHeight
  }
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleTimeString()
}

// 页面加载
onMounted(() => {
  loadChatRooms()
})
</script>

<style lang="scss" scoped>
.chat-container {
  height: 100vh;
  display: flex;
  background: #f5f5f5;
}

.chat-sidebar {
  width: 300px;
  background: white;
  border-right: 1px solid #eee;
  display: flex;
  flex-direction: column;
  
  .sidebar-header {
    padding: 16px;
    border-bottom: 1px solid #eee;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    h3 {
      margin: 0;
    }
  }
  
  .room-list {
    flex: 1;
    overflow-y: auto;
    
    .room-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 16px;
      cursor: pointer;
      border-bottom: 1px solid #f0f0f0;
      
      &:hover, &.active {
        background: #f8f9fa;
      }
      
      .room-info {
        h4 {
          margin: 0 0 4px 0;
          font-size: 14px;
        }
        
        p {
          margin: 0;
          font-size: 12px;
          color: #666;
        }
      }
    }
  }
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  
  .no-room {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .chat-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    background: white;
    
    .chat-header {
      padding: 16px;
      border-bottom: 1px solid #eee;
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .room-info {
        h3 {
          margin: 0 0 4px 0;
        }
        
        p {
          margin: 0;
          font-size: 12px;
          color: #666;
        }
      }
    }
    
    .message-list {
      flex: 1;
      overflow-y: auto;
      padding: 16px;
      
      .message-item {
        display: flex;
        gap: 12px;
        margin-bottom: 16px;
        
        &.own-message {
          flex-direction: row-reverse;
          
          .message-content {
            background: #007bff;
            color: white;
          }
        }
        
        .message-content {
          background: #f8f9fa;
          padding: 8px 12px;
          border-radius: 8px;
          max-width: 70%;
          
          .message-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 4px;
            font-size: 12px;
            opacity: 0.7;
          }
          
          .message-text {
            line-height: 1.4;
          }
        }
      }
    }
    
    .message-input {
      padding: 16px;
      border-top: 1px solid #eee;
      display: flex;
      gap: 12px;
      align-items: flex-end;
      
      .el-textarea {
        flex: 1;
      }
    }
  }
}

.member-list {
  .member-item {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 8px 0;
    
    .member-name {
      flex: 1;
    }
  }
}

@media (max-width: 768px) {
  .chat-sidebar {
    width: 250px;
  }
}
</style>
